package com.jujia.tmall.base;


import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;


import com.elune.ui.ConnectionToast;
import com.jujia.tmall.activity.R;
import com.jujia.tmall.util.StatusBarUtil;

import android.support.v7.app.AppCompatActivity;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


/**
 * Fragment情况下的拍照图片缓存 防止崩溃 安卓自带标题隐藏 多个Activity安全退出
 *
 * @author Elune1943
 */
public class BaseActivity extends AppCompatActivity {

    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;

    protected SharedPreferences spBase;
    protected SharedPreferences.Editor editorBase;
    protected Context mContext;
    private ViewFlipper mContentView;

    protected Toolbar toolbar;
    protected View mFakeStatusBar;
    public ActToolBarOnClickListener mToolBarOnClickListener;

    /**高德*/
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private static final int PERMISSON_REQUESTCODE = 0;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;

    /**高德*/


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);


        super.setContentView(R.layout.layout_base);

        // 初始化公共头部
        mContentView = (ViewFlipper) super.findViewById(R.id.layout_container);
        mContext = this;
        /*融云-end*/
//        loadingDialog = new ObdDialog(BaseRyActivity.this, R.style.obd_dialog);
        spBase = getSharedPreferences(SealConst.BASE_XML, MODE_PRIVATE);
        editorBase = spBase.edit();
    }


    @Override
    public void setContentView(View view) {

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1);
        mContentView.addView(view, lp);

    }

    @Override
    public void setContentView(int layoutResID) {
        View view = LayoutInflater.from(this).inflate(layoutResID, null);
        setContentView(view);
    }


    protected void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            showAlertDialog("需要权限", rationale,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(BaseActivity.this,
                                    new String[]{permission}, requestCode);
                        }
                    }, "确定", null, "取消");
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    private AlertDialog mAlertDialog;


    protected void showAlertDialog(@Nullable String title, @Nullable String message,
                                   @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                                   @NonNull String positiveText,
                                   @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                                   @NonNull String negativeText) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
        mAlertDialog = builder.show();
    }


    public String getBaseBraceletXml(String key, String value) {
        return spBase.getString(key, value);
    }

    public void setBraceletXml(String key, String value) {
        editorBase.putString(key, value);
        editorBase.commit();
    }

    protected void toastActMid(String str) {
        ConnectionToast.ToastShowMid(this, str);
    }

    protected void toastActBtm(String str) {
        ConnectionToast.ToastShowBottom(this, str);
    }


    public void setMenuTitle(int type, int isStatus, String title, int back, int rightMenu) {
        setNewTitle(true, this, isStatus, title, R.color.colorTheme, back, rightMenu);

    }


    /**
     * @param isRemoveStatus 是否移除状态栏 true 移除
     * @param context
     * @param statusColor    状态栏颜色 0为不显示
     * @param titleStr       标题
     * @param toolBarBag     标题背景色
     * @param navagationIcon 标题左侧图片 0 为不显示
     * @param rightMenu      标题右侧图片集合 0 为不显示
     */
    public void setNewTitle(boolean isRemoveStatus, final Activity context, int statusColor, String titleStr, int toolBarBag, int navagationIcon, int rightMenu) {


        if (isRemoveStatus) {
            StatusBarUtil.setTranslucentForImageViewInFragment(context, 0, null);
        }
        mFakeStatusBar = findViewById(R.id.fake_status_bar);
        if (statusColor != 0) {
            mFakeStatusBar.setVisibility(View.VISIBLE);
            mFakeStatusBar.setBackgroundResource(statusColor);
        } else {
            mFakeStatusBar.setVisibility(View.GONE);
        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);

        if (toolBarBag != 0) {
            toolbar.setBackgroundResource(toolBarBag);
        } else {
            toolbar.setBackgroundResource(R.color.transparent);
        }

        if (navagationIcon != 0) {
            toolbar.setNavigationIcon(navagationIcon);//设置导航栏图标
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mToolBarOnClickListener.leftClick();
                }
            });
        }

        if (titleStr != null) {
            toolbar.setTitle(titleStr);//设置主标题
            toolbar.setTitleTextColor(context.getResources().getColor(R.color.white));
        }

        if (rightMenu != 0) {
            if (toolbar.getMenu().size() < 1) {
                toolbar.inflateMenu(rightMenu);//设置右上角的填充菜单
                toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        if (DoubleClickUtil.check()) {
//                            ConnectionToast.ToastShowBottom(context, "请勿频繁操作！");
                            return false;
                        } else {
                            mToolBarOnClickListener.rightMenuClick(item);
                            return true;
                        }

                    }
                });
            }
        }


    }

    public interface ActToolBarOnClickListener {
        void leftClick();

        void rightMenuClick(MenuItem item);

    }


    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

        if (mAlertDialog != null && mAlertDialog.isShowing()) {
            mAlertDialog.dismiss();
        }
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();


    }

    /**高德*/
    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            if (isNeedCheck) {
                checkPermissions(needPermissions);
            }
        }
    }

    /**
     *
     * @param permissions
     * @since 2.5.0
     *
     */
    private void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class,
                            int.class});

                    method.invoke(this, array, PERMISSON_REQUESTCODE);
                }
            }
        } catch (Throwable e) {
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     *
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23){
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer)checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean)shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {

            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否所有的权限都已经授权
     * @param grantResults
     * @return
     * @since 2.5.0
     *
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     *
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(com.jujia.tmall.activity.R.string.notifyTitle);
        builder.setMessage(com.jujia.tmall.activity.R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(com.jujia.tmall.activity.R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton(com.jujia.tmall.activity.R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     *  启动应用的设置
     *
     * @since 2.5.0
     *
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

}
